#include "Detection.h"

Detection::Detection(void)
{
}

//Perform face detection on the input image, using the given Haar Cascade
//Returns a rectangle for the detected region in the given image
CvRect Detection::DetectFaceInImage(IplImage * inputImg, CvHaarClassifierCascade * faceCascade)
{
	//Smallest face size
	CvSize minFeatureSize = cvSize(20, 20);

	//Only search for 1 face
	int flags = CV_HAAR_FIND_BIGGEST_OBJECT | CV_HAAR_DO_ROUGH_SEARCH;

	//How detailed should the search be
	float search_scale_factor = 1.1f;
	CvMemStorage * storage;
	CvRect rc;
	double t;
	CvSeq * rects;
	int ms, nFaces;

	//Memory storage
	storage = cvCreateMemStorage(0);
	cvClearMemStorage(storage);

	//Detect all the faces in the greyscale image
	t = (double)cvGetTickCount();

	rects = cvHaarDetectObjects(inputImg, faceCascade, storage, search_scale_factor, 3, flags, minFeatureSize);

	t = (double)cvGetTickCount() - t;

	ms = cvRound( t / ((double)cvGetTickFrequency() * 1000.0) );

	nFaces = rects->total;
	//std::cout << "Face Detection took " << ms << " ms and found " << nFaces << " objects\n";

	//Get the first detected face (the biggest)
	if (nFaces > 0)
		rc = *(CvRect*)cvGetSeqElem(rects, 0);
	else
		rc = cvRect(-1,-1,-1,-1);	// Couldn't find the face

	//Release memory
	cvReleaseMemStorage( &storage );

	return rc;	//Return the biggest face found, or (-1,-1,-1,-1).
}

Detection::~Detection(void)
{
}
